using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Identity;
using WMSSystem.Application.Contracts.Workflow;
using WMSSystem.Application.Contracts.Workflow.Dto;
using WMSSystem.Domain.Workflow;
using WorkflowCore.Interface;

namespace WMSSystem.Application.Workflow
{
    /// <summary>
    /// 工作流服务实现
    /// </summary>
    public class WorkflowService : ApplicationService, IWorkflowService
    {
        private readonly IWorkflowHost _workflowHost;
        private readonly IRepository<WorkflowInstance, Guid> _workflowInstanceRepository;
        private readonly IRepository<WorkflowApproval, Guid> _workflowApprovalRepository;
        private readonly IRepository<IdentityUser, Guid> _userRepository;
        private readonly ILogger<WorkflowService> _logger;

        public WorkflowService(
            IWorkflowHost workflowHost,
            IRepository<WorkflowInstance, Guid> workflowInstanceRepository,
            IRepository<WorkflowApproval, Guid> workflowApprovalRepository,
            IRepository<IdentityUser, Guid> userRepository,
            ILogger<WorkflowService> logger)
        {
            _workflowHost = workflowHost;
            _workflowInstanceRepository = workflowInstanceRepository;
            _workflowApprovalRepository = workflowApprovalRepository;
            _userRepository = userRepository;
            _logger = logger;
        }

        /// <summary>
        /// 创建工作流实例
        /// </summary>
        public async Task<ApiResponse<string>> CreateWorkflowInstanceAsync(CreateWorkflowInstanceDto input)
        {
            try
            {
                _logger.LogInformation($"开始创建工作流实例: {input.WorkflowDefinitionId}");
                
                // 启动工作流
                var workflowId = await _workflowHost.StartWorkflow(input.WorkflowDefinitionId, input.WorkflowData);
                _logger.LogInformation($"工作流启动成功，ID: {workflowId}");

                // 保存工作流实例记录
                var workflowInstance = new WorkflowInstance
                {
                    WorkflowInstanceId = workflowId,
                    WorkflowDefinitionId = input.WorkflowDefinitionId,
                    BusinessType = input.BusinessType,
                    BusinessId = input.BusinessId,
                    Status = "Running",
                    CurrentStep = "ManagerApproval",
                    WorkflowData = input.WorkflowData,
                    Remark = input.Remark
                };

                await _workflowInstanceRepository.InsertAsync(workflowInstance);
                _logger.LogInformation($"工作流实例记录保存成功: {workflowId}");

                return new ApiResponse<string>
                {
                    Code = ErrorCode.Success,
                    Message = "创建工作流实例成功",
                    Data = workflowId
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建工作流实例失败");
                return new ApiResponse<string>
                {
                    Code = ErrorCode.Error,
                    Message = $"创建工作流实例失败: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 审批工作流
        /// </summary>
        public async Task<ApiResponse<bool>> ApproveWorkflowAsync(WorkflowApprovalDto input)
        {
            try
            {
                // 获取工作流实例
                var workflowInstance = await _workflowInstanceRepository.FirstOrDefaultAsync(x => x.WorkflowInstanceId == input.WorkflowInstanceId.ToString());
                if (workflowInstance == null)
                {
                    return new ApiResponse<bool>
                    {
                        Code = ErrorCode.Error,
                        Message = "工作流实例不存在",
                        Data = false
                    };
                }

                // 使用传入的审批人信息或当前用户
                Guid approverId;
                string approverName;
                
                if (!string.IsNullOrEmpty(input.ApproverId) && Guid.TryParse(input.ApproverId, out var inputApproverId))
                {
                    approverId = inputApproverId;
                    approverName = input.ApproverName ?? "未知用户";
                }
                else
                {
                    // 获取当前用户
                    var currentUser = CurrentUser;
                    if (currentUser?.Id == null)
                    {
                        return new ApiResponse<bool>
                        {
                            Code = ErrorCode.Error,
                            Message = "用户未登录",
                            Data = false
                        };
                    }
                    approverId = currentUser.Id.Value;
                    approverName = currentUser.UserName ?? "未知用户";
                }

                // 保存审批记录
                var approvalRecord = new WorkflowApproval
                {
                    WorkflowInstanceId = workflowInstance.Id,
                    StepName = input.StepName,
                    ApproverId = approverId,
                    ApproverName = approverName,
                    ApprovalResult = input.ApprovalResult,
                    ApprovalComment = input.ApprovalComment,
                    ApprovalTime = DateTime.Now,
                    SortOrder = await GetNextSortOrder(workflowInstance.Id)
                };

                await _workflowApprovalRepository.InsertAsync(approvalRecord);

                // 发送工作流事件
                if (input.ApprovalResult == "Approved")
                {
                    await _workflowHost.PublishEvent(input.StepName, workflowInstance.WorkflowInstanceId, input.ApprovalResult);
                }
                else
                {
                    // 拒绝时结束工作流
                    workflowInstance.Status = "Rejected";
                    await _workflowInstanceRepository.UpdateAsync(workflowInstance);
                }

                return new ApiResponse<bool>
                {
                    Code = ErrorCode.Success,
                    Message = "审批成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "审批工作流失败");
                return new ApiResponse<bool>
                {
                    Code = ErrorCode.Error,
                    Message = $"审批失败: {ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 获取工作流实例
        /// </summary>
        public async Task<ApiResponse<WorkflowInstanceDto>> GetWorkflowInstanceAsync(string workflowInstanceId)
        {
            try
            {
                var workflowInstance = await _workflowInstanceRepository.FirstOrDefaultAsync(x => x.WorkflowInstanceId == workflowInstanceId);
                if (workflowInstance == null)
                {
                    return new ApiResponse<WorkflowInstanceDto>
                    {
                        Code = ErrorCode.Error,
                        Message = "工作流实例不存在",
                        Data = null
                    };
                }

                var dto = await MapToWorkflowInstanceDto(workflowInstance);
                return new ApiResponse<WorkflowInstanceDto>
                {
                    Code = ErrorCode.Success,
                    Message = "获取工作流实例成功",
                    Data = dto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流实例失败");
                return new ApiResponse<WorkflowInstanceDto>
                {
                    Code = ErrorCode.Error,
                    Message = $"获取工作流实例失败: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 获取业务相关的工作流实例
        /// </summary>
        public async Task<ApiResponse<WorkflowInstanceDto>> GetWorkflowInstanceByBusinessAsync(string businessType, Guid businessId)
        {
            try
            {
                var workflowInstance = await _workflowInstanceRepository.FirstOrDefaultAsync(x => x.BusinessType == businessType && x.BusinessId == businessId);
                if (workflowInstance == null)
                {
                    return new ApiResponse<WorkflowInstanceDto>
                    {
                        Code = ErrorCode.Error,
                        Message = "未找到相关的工作流实例",
                        Data = null
                    };
                }

                var dto = await MapToWorkflowInstanceDto(workflowInstance);
                return new ApiResponse<WorkflowInstanceDto>
                {
                    Code = ErrorCode.Success,
                    Message = "获取工作流实例成功",
                    Data = dto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取业务工作流实例失败");
                return new ApiResponse<WorkflowInstanceDto>
                {
                    Code = ErrorCode.Error,
                    Message = $"获取业务工作流实例失败: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 获取工作流实例列表
        /// </summary>
        public async Task<ApiResponse<List<WorkflowInstanceDto>>> GetWorkflowInstancesAsync()
        {
            try
            {
                var instances = await _workflowInstanceRepository.GetListAsync();
                var dtos = instances.Select(x => new WorkflowInstanceDto
                {
                    WorkflowInstanceId = x.WorkflowInstanceId,
                    WorkflowDefinitionId = x.WorkflowDefinitionId,
                    BusinessType = x.BusinessType,
                    BusinessId = x.BusinessId,
                    Status = x.Status,
                    CreationTime = x.CreationTime
                }).ToList();

                return new ApiResponse<List<WorkflowInstanceDto>>
                {
                    Code = ErrorCode.Success,
                    Message = "获取工作流实例列表成功",
                    Data = dtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流实例列表失败");
                return new ApiResponse<List<WorkflowInstanceDto>>
                {
                    Code = ErrorCode.Error,
                    Message = $"获取工作流实例列表失败: {ex.Message}",
                    Data = new List<WorkflowInstanceDto>()
                };
            }
        }

        /// <summary>
        /// 获取工作流状态
        /// </summary>
        public async Task<ApiResponse<object>> GetWorkflowStatusAsync(string workflowInstanceId)
        {
            try
            {
                // 从数据库获取工作流实例信息
                var instance = await _workflowInstanceRepository.FindAsync(x => x.WorkflowInstanceId == workflowInstanceId);
                if (instance == null)
                {
                    return new ApiResponse<object>
                    {
                        Code = ErrorCode.Error,
                        Message = "工作流实例不存在",
                        Data = null
                    };
                }

                var status = new
                {
                    WorkflowInstanceId = instance.WorkflowInstanceId,
                    Status = instance.Status,
                    BusinessType = instance.BusinessType,
                    BusinessId = instance.BusinessId,
                    CreationTime = instance.CreationTime
                };

                return new ApiResponse<object>
                {
                    Code = ErrorCode.Success,
                    Message = "获取工作流状态成功",
                    Data = status
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流状态失败");
                return new ApiResponse<object>
                {
                    Code = ErrorCode.Error,
                    Message = $"获取工作流状态失败: {ex.Message}",
                    Data = null
                };
            }
        }

        /// <summary>
        /// 获取待审批列表
        /// </summary>
        public async Task<ApiResponse<List<WorkflowInstanceDto>>> GetPendingApprovalListAsync(Guid approverId)
        {
            try
            {
                var query = await _workflowInstanceRepository.GetQueryableAsync();
                var pendingWorkflows = query.Where(x => x.Status == "Running" && x.CurrentApproverId == approverId).ToList();

                var dtos = new List<WorkflowInstanceDto>();
                foreach (var workflow in pendingWorkflows)
                {
                    var dto = await MapToWorkflowInstanceDto(workflow);
                    dtos.Add(dto);
                }

                return new ApiResponse<List<WorkflowInstanceDto>>
                {
                    Code = ErrorCode.Success,
                    Message = "获取待审批列表成功",
                    Data = dtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取待审批列表失败");
                return new ApiResponse<List<WorkflowInstanceDto>>
                {
                    Code = ErrorCode.Error,
                    Message = $"获取待审批列表失败: {ex.Message}",
                    Data = new List<WorkflowInstanceDto>()
                };
            }
        }

        /// <summary>
        /// 获取待审批列表（所有）
        /// </summary>
        public async Task<ApiResponse<List<WorkflowInstanceDto>>> GetPendingApprovalsAsync()
        {
            try
            {
                var instances = await _workflowInstanceRepository.GetListAsync(x => x.Status == "Pending");
                var dtos = instances.Select(x => new WorkflowInstanceDto
                {
                    WorkflowInstanceId = x.WorkflowInstanceId,
                    WorkflowDefinitionId = x.WorkflowDefinitionId,
                    BusinessType = x.BusinessType,
                    BusinessId = x.BusinessId,
                    Status = x.Status,
                    CreationTime = x.CreationTime
                }).ToList();

                return new ApiResponse<List<WorkflowInstanceDto>>
                {
                    Code = ErrorCode.Success,
                    Message = "获取待审批列表成功",
                    Data = dtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取待审批列表失败");
                return new ApiResponse<List<WorkflowInstanceDto>>
                {
                    Code = ErrorCode.Error,
                    Message = $"获取待审批列表失败: {ex.Message}",
                    Data = new List<WorkflowInstanceDto>()
                };
            }
        }

        /// <summary>
        /// 获取我的审批记录
        /// </summary>
        public async Task<ApiResponse<List<WorkflowInstanceDto>>> GetMyApprovalHistoryAsync(Guid approverId)
        {
            try
            {
                var approvalQuery = await _workflowApprovalRepository.GetQueryableAsync();
                var myApprovals = approvalQuery.Where(x => x.ApproverId == approverId)
                    .Select(x => x.WorkflowInstanceId)
                    .Distinct()
                    .ToList();

                var workflowQuery = await _workflowInstanceRepository.GetQueryableAsync();
                var workflows = workflowQuery.Where(x => myApprovals.Contains(x.Id)).ToList();

                var dtos = new List<WorkflowInstanceDto>();
                foreach (var workflow in workflows)
                {
                    var dto = await MapToWorkflowInstanceDto(workflow);
                    dtos.Add(dto);
                }

                return new ApiResponse<List<WorkflowInstanceDto>>
                {
                    Code = ErrorCode.Success,
                    Message = "获取审批记录成功",
                    Data = dtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取审批记录失败");
                return new ApiResponse<List<WorkflowInstanceDto>>
                {
                    Code = ErrorCode.Error,
                    Message = $"获取审批记录失败: {ex.Message}",
                    Data = new List<WorkflowInstanceDto>()
                };
            }
        }

        /// <summary>
        /// 映射到DTO
        /// </summary>
        private async Task<WorkflowInstanceDto> MapToWorkflowInstanceDto(WorkflowInstance workflowInstance)
        {
            var dto = ObjectMapper.Map<WorkflowInstance, WorkflowInstanceDto>(workflowInstance);

            // 获取当前审批人姓名
            if (workflowInstance.CurrentApproverId.HasValue)
            {
                var approver = await _userRepository.GetAsync(workflowInstance.CurrentApproverId.Value);
                dto.CurrentApproverName = approver.UserName;
            }

            // 获取审批记录
            var approvalQuery = await _workflowApprovalRepository.GetQueryableAsync();
            var approvals = approvalQuery.Where(x => x.WorkflowInstanceId == workflowInstance.Id)
                .OrderBy(x => x.SortOrder)
                .ToList();

            dto.ApprovalRecords = approvals.Select(x => new WorkflowApprovalRecordDto
            {
                StepName = x.StepName,
                ApproverName = x.ApproverName,
                ApprovalResult = x.ApprovalResult,
                ApprovalComment = x.ApprovalComment,
                ApprovalTime = x.ApprovalTime
            }).ToList();

            return dto;
        }

        /// <summary>
        /// 获取下一个排序号
        /// </summary>
        private async Task<int> GetNextSortOrder(Guid workflowInstanceId)
        {
            var approvalQuery = await _workflowApprovalRepository.GetQueryableAsync();
            var maxSortOrder = approvalQuery.Where(x => x.WorkflowInstanceId == workflowInstanceId)
                .Max(x => (int?)x.SortOrder) ?? 0;
            return maxSortOrder + 1;
        }
    }
} 